import { GameState, FruitType } from '../types/game';
import { getRandomInitialFruit } from '../config/fruits';

export class GameStateManager {
  private state: GameState;
  private listeners: ((state: GameState) => void)[] = [];
  private readonly STORAGE_KEY = 'watermelon-game-high-score';

  constructor() {
    this.state = this.getInitialState();
    this.loadHighScore();
  }

  // 获取初始游戏状态
  private getInitialState(): GameState {
    return {
      score: 0,
      highScore: 0,
      currentFruit: getRandomInitialFruit(),
      nextFruit: getRandomInitialFruit(),
      isGameOver: false,
      isPlaying: false,
      fruits: []
    };
  }

  // 从本地存储加载最高分
  private loadHighScore(): void {
    try {
      const saved = localStorage.getItem(this.STORAGE_KEY);
      if (saved) {
        this.state.highScore = parseInt(saved, 10) || 0;
        this.notifyListeners();
      }
    } catch (error) {
      console.warn('Failed to load high score:', error);
    }
  }

  // 保存最高分到本地存储
  private saveHighScore(): void {
    try {
      localStorage.setItem(this.STORAGE_KEY, this.state.highScore.toString());
    } catch (error) {
      console.warn('Failed to save high score:', error);
    }
  }

  // 获取当前状态
  public getState(): GameState {
    return { ...this.state };
  }

  // 订阅状态变化
  public subscribe(listener: (state: GameState) => void): () => void {
    this.listeners.push(listener);
    
    // 返回取消订阅函数
    return () => {
      const index = this.listeners.indexOf(listener);
      if (index > -1) {
        this.listeners.splice(index, 1);
      }
    };
  }

  // 通知所有监听器
  private notifyListeners(): void {
    this.listeners.forEach(listener => listener(this.getState()));
  }

  // 开始游戏
  public startGame(): void {
    this.state = {
      ...this.getInitialState(),
      highScore: this.state.highScore,
      isPlaying: true
    };
    this.notifyListeners();
  }

  // 暂停/恢复游戏
  public togglePause(): void {
    if (!this.state.isGameOver) {
      this.state.isPlaying = !this.state.isPlaying;
      this.notifyListeners();
    }
  }

  // 增加分数
  public addScore(points: number): void {
    this.state.score += points;
    
    // 检查是否创造新纪录
    if (this.state.score > this.state.highScore) {
      this.state.highScore = this.state.score;
      this.saveHighScore();
    }
    
    this.notifyListeners();
  }

  // 更新当前水果（投放后）
  public updateCurrentFruit(): void {
    this.state.currentFruit = this.state.nextFruit;
    this.state.nextFruit = getRandomInitialFruit();
    this.notifyListeners();
  }

  // 游戏结束
  public gameOver(): void {
    this.state.isGameOver = true;
    this.state.isPlaying = false;
    this.notifyListeners();
  }

  // 重置游戏
  public resetGame(): void {
    this.state = {
      ...this.getInitialState(),
      highScore: this.state.highScore
    };
    this.notifyListeners();
  }

  // 获取分数统计
  public getScoreStats(): {
    current: number;
    high: number;
    isNewRecord: boolean;
    percentage: number;
  } {
    const isNewRecord = this.state.score === this.state.highScore && this.state.score > 0;
    const percentage = this.state.highScore > 0 ? (this.state.score / this.state.highScore) * 100 : 0;
    
    return {
      current: this.state.score,
      high: this.state.highScore,
      isNewRecord,
      percentage
    };
  }

  // 获取游戏进度信息
  public getGameProgress(): {
    fruitsDropped: number;
    highestFruitLevel: number;
    averageScore: number;
  } {
    const fruitsDropped = this.state.fruits.length;
    const highestFruitLevel = this.state.fruits.length > 0 
      ? Math.max(...this.state.fruits.map(fruit => fruit.type.id)) 
      : 0;
    const averageScore = fruitsDropped > 0 ? this.state.score / fruitsDropped : 0;
    
    return {
      fruitsDropped,
      highestFruitLevel,
      averageScore: Math.round(averageScore * 100) / 100
    };
  }

  // 检查是否达到成就
  public checkAchievements(): string[] {
    const achievements: string[] = [];
    const progress = this.getGameProgress();
    
    // 分数成就
    if (this.state.score >= 1000) achievements.push('得分达人');
    if (this.state.score >= 5000) achievements.push('合成大师');
    if (this.state.score >= 10000) achievements.push('西瓜传说');
    
    // 水果等级成就
    if (progress.highestFruitLevel >= 7) achievements.push('菠萝达成');
    if (progress.highestFruitLevel >= 8) achievements.push('椰子达成');
    if (progress.highestFruitLevel >= 9) achievements.push('西瓜达成');
    
    // 效率成就
    if (progress.averageScore >= 10) achievements.push('效率专家');
    
    return achievements;
  }

  // 保存游戏进度（可用于续玩功能）
  public saveGameProgress(): void {
    try {
      const gameData = {
        score: this.state.score,
        timestamp: Date.now()
      };
      localStorage.setItem('watermelon-game-progress', JSON.stringify(gameData));
    } catch (error) {
      console.warn('Failed to save game progress:', error);
    }
  }

  // 加载游戏进度
  public loadGameProgress(): boolean {
    try {
      const saved = localStorage.getItem('watermelon-game-progress');
      if (saved) {
        const gameData = JSON.parse(saved);
        
        // 检查是否在24小时内
        const now = Date.now();
        const hoursPassed = (now - gameData.timestamp) / (1000 * 60 * 60);
        
        if (hoursPassed < 24) {
          this.state.score = gameData.score;
          this.notifyListeners();
          return true;
        }
      }
    } catch (error) {
      console.warn('Failed to load game progress:', error);
    }
    
    return false;
  }

  // 清除保存的进度
  public clearGameProgress(): void {
    try {
      localStorage.removeItem('watermelon-game-progress');
    } catch (error) {
      console.warn('Failed to clear game progress:', error);
    }
  }
}